<template>
    <el-container>
        <!-- <el-header>
            <div class="left-panel"></div>
            <div class="right-panel">
                <el-button @click="visible = false">取 消</el-button>
                <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
                <el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
            </div>
        </el-header> -->
        <el-main class="nopadding">
            <el-card>
                <template #header>
                    <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
                        <span style="padding-right:20px">{{ mode == 'show' ? '查看销售单' : mode == 'edit' ? '编辑销售单' : '新增销售单' }}</span>
                        <div class="right-panel">
                            <el-button @click="close">取 消</el-button>
                            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
                            <el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
                        </div>
                    </div>
                </template>
                <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-position="top">
                    <el-row :gutter="1">
                        <el-col :span="6">
                            <el-form-item label="销售单号" prop="contract_code">
                                <el-input v-model="form.contract_code" placeholder="销售单号(不填写自动生成)" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="销售日期" prop="open_single">
                                <el-date-picker v-model="form.open_single" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="销售人员" prop="seller_id">
                                <el-select v-model="form.seller_id" filterable clearable placeholder="请选择销售人员" style="width:100%">
                                    <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-col :span="24">
                        <el-form-item label="产品清单" prop="order_detail">
                            <sc-form-table class="formtable" ref="table" v-model="order_detail" :addTemplate="addTemplate" placeholder="暂无数据" height="550" :cell-style="cellStyle" show-summary>
                                <el-table-column prop="goods" label="产品型号" align="center" width="200">
                                    <template #default="scope">
                                        <sc-table-select v-model="scope.row.goods_obj" filterable :apiObj="goodsApiObj" :params="goodsParams" :table-width="800" :props="props" @change="goodsChange(scope.row)" border :height="400" :is_stock="1">
                                            <el-table-column prop="id" label="ID" width="60"></el-table-column>
                                            <el-table-column prop="goods_model" label="产品型号" width="200"></el-table-column>
                                            <el-table-column prop="color" label="颜色"></el-table-column>
                                            <el-table-column prop="direction" label="方向"></el-table-column>
                                            <el-table-column prop="speed_ratio_name" label="速比"></el-table-column>
                                            <el-table-column prop="flange_name" label="法兰"></el-table-column>
                                            <!-- <el-table-column prop="color_name" label="颜色"></el-table-column> -->
                                            <el-table-column prop="hole" label="孔数"></el-table-column>
                                            <el-table-column prop="ware_num" label="库存数量"></el-table-column>
                                        </sc-table-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="颜色" align="center" width="140">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.color_type" filterable style="width: 100%" placeholder="颜色">
                                            <el-option v-for="item in colorList" :key="item.id" :label="item.name" :value="item.id" />
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="方向" align="center" width="140">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.direction_type" filterable style="width: 100%" placeholder="方向">
                                            <el-option v-for="item in directionList" :key="item.id" :label="item.name" :value="item.id" />
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="速比" align="center" width="80">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.speed_ratio_name" placeholder="速比" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="法兰" align="center" width="140">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.flange_name" placeholder="法兰" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="孔数" align="center" width="80">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.hole" placeholder="孔数"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" prop="sale_num" align="center" width="80">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.sale_num" placeholder="数量" @input="totalCompute"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="使用现货" align="center" width="80">
                                    <template #default="scope">
                                        {{scope.row.ware_num}}
                                        <el-switch v-model="scope.row.is_stock" :active-value="1" active-color="#13ce66" :inactive-value="0" inactive-color="#ff4949" inline-prompt active-text="是" inactive-text="否"></el-switch>
                                    </template>
                                </el-table-column>
                                <el-table-column label="单价" align="center" width="80">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="小计" prop="total_price" align="center" width="100">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.total_price" placeholder="小计" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="客户" align="center" width="160">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.customer_id" filterable style="width: 100%" placeholder="客户">
                                            <el-option v-for="item in clientList" :key="item.id" :label="item.customer_name" :value="item.id" />
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="备注1" align="center" width="130">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.remark1" placeholder="备注1" @input="remarkInput(scope.row)" type="textarea" :rows="3"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="备注2" align="center" width="130">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.remark2" placeholder="备注2" type="textarea" :rows="3"></el-input>
                                    </template>
                                </el-table-column>
                            </sc-form-table>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-card>
        </el-main>
        <el-footer style="height: 51px;"></el-footer>
    </el-container>
</template>

<script>
import useTabs from '@/utils/useTabs'
export default {
    name: '新增销售',
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增销售订单',
                edit: '编辑销售订单',
                show: '查看'
            },
            visible: false,
            isSaveing: false,
            //表单数据
            form: {
                id: "",
                seller_id: this.$TOOL.data.get("USER_INFO").admin_id,
                contract_code: "",
                open_single: this.moment().format('YYYY-MM-DD'),
                customer_id: '1',
                contacts: '1',
                contract_price: "",
                is_check: 0,
            },
            contactList: [],
            unitList: [],
            adminList: [],
            speedList: [],
            flangeList: [],
            colorList: [],
            directionList: [],
            clientList: [],
            addTemplate: { sale_num: 1, goods_model: '', speed_ratio_id: '', flange_id: '', color_type: '', price: '', customer_id: '',goods_obj: {
                goods_model: "",
                goods_id: "",
            },},
            dialog: {
                goods: false,
            },
            order_detail: [],
            accountList: [],
            list: [],
            loading: false,
            goodsApiObj: this.$API.goods.goods.list,
            
            props: {
                label: 'goods_model',
                value: 'goods_id',
                keyword: "goods_model"
            },
        }
    },
    mounted() {
        if (this.$route.query.id) {
            this.setData()
            this.mode = this.$route.query.zhuangtai
        }
        this.getCate()  //分类
        this.getUnit() // 单位
        this.getAdmin()
        this.getClient() // 客户
        this.getColor() // 颜色
        this.getDirection() // 方向
    },
    methods: {
        change(val) {
            this.$message('change事件，返回详情查看控制台')
            console.log(val)
        },
        async getAllGoods() {
            var res = await this.$API.contract.contract.getallproduct.get();
            this.list = res.data;
        },
        async remoteMethod(query) {
            var res = await this.$API.contract.contract.getallproduct.get({ keyword: query });
            if (query) {
                this.loading = true
                setTimeout(() => {
                    this.loading = false
                    this.goodsList = res.data.filter((item) => {
                        return item.goods_name.includes(query)
                    })
                }, 200)
            } else {
                this.goodsList = []
            }
        },
        close() {
            useTabs.close()
            this.$router.back(-1)
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit(e) {
            this.form.is_check = e
            let price = true;
            let sale_num = true;
            let customer_id = true;
            let array = [];
            let price_error_rows = [];
            let sale_num_error_rows = [];
            let customer_id_error_rows = [];
            this.order_detail.map((item, index) => {
                console.log(index);
                if (item.price <= 0) {
                    price = false;
                    price_error_rows.push(index);
                }
                if (item.sale_num <= 0) {
                    sale_num = false;
                    sale_num_error_rows.push(index);
                }
                if (item.customer_id === '') {
                    customer_id = false;
                    customer_id_error_rows.push(index);
                }
                array.push({
                    id: item.id,
                    goods_model: item.goods_model,
                    speed_ratio_id: item.speed_ratio_id,
                    flange_id: item.flange_id,
                    color_id: item.color_id,
                    color_type: item.color_type,
                    direction_type: item.direction_type,
                    price: item.price,
                    sale_num: item.sale_num,
                    hole: item.hole,
                    total_price: item.total_price,
                    customer_id: item.customer_id,
                    remark1: item.remark1,
                    remark2: item.remark2,
                    is_stock: item.is_stock
                });
            });
            this.form.order_detail = array;
            if (!price) {
                let errorMsg = "产品单价不可为0,请检查以下行: ";
                price_error_rows.forEach((row) => {
                    errorMsg += row + 1 + ",";
                });
                this.$message.error(errorMsg);
            } else if (!sale_num) {
                let errorMsg = "产品数量不可为0,请检查以下行: ";
                sale_num_error_rows.forEach((row) => {
                    errorMsg += row + 1 + ",";
                });
                this.$message.error(errorMsg);
            } else if (!customer_id) {
                let errorMsg = "存在未选择客户列,请检查以下行: ";
                customer_id_error_rows.forEach((row) => {
                    errorMsg += row + 1 + ",";
                });
                this.$message.error(errorMsg);
            } else {
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res = [];
                        if (this.form.id) {
                            res = await this.$API.contract.contract.edit.post(this.form);
                        } else {
                            res = await this.$API.contract.contract.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if (res.code == 1) {
                            useTabs.close()
                            this.$router.back(-1)
                            this.$emit('success', this.form, this.mode)
                            this.$message.success("操作成功")
                        } else {
                            this.$alert(res.message, "提示", { type: 'error' })
                        }
                    } else {
                        return false;
                    }
                })
            }
        },
        //表单注入数据
        async setData() {
            this.form.id = this.$route.query.id
            var res = await this.$API.contract.contract.detail.get({ id: this.$route.query.id });
            this.form.seller_id = res.data.seller_id
            this.form.open_single = res.data.open_single
            this.form.contract_code = res.data.contract_code
            let array = []
            res.data.order_detail.map(item => {
                array.push({
                    id: item.id,
                    goods_obj: item,
                    goods_model: item.goods_model,
                    ware_num: item.ware_num,
                    goods_model_name: item.goods_model,
                    sale_num: item.sale_num,
                    price: item.price,
                    total_price: item.total_price,
                    speed_ratio_id: item.speed_ratio_id ? item.speed_ratio_id : '',
                    flange_id: item.flange_id ? item.flange_id : '',
                    color_id: item.color_id ? item.color_id : '',
                    color_type: item.color_type,
                    direction_type: item.direction_type,
                    hole: item.hole,
                    customer_id: item.customer_id,
                    speed_ratio_name: item.speedRatio.name,
                    flange_name: item.flange.name,
                    color_name: item.color.name,
                    remark1: item.remark1,
                    remark2: item.remark2,
                    is_stock: item.is_stock,

                })
            })
            this.order_detail = array
            this.totalCompute()
        },
        totalCompute() {
            let count_price = 0
            this.form.contract_price = 0
            this.form.total_price = 0
            this.order_detail.map(item => {
                if (item.price && item.sale_num) {
                    count_price = Number(count_price) + (Number(item.sale_num) * Number(item.price))
                    item.total_price = (Number(item.sale_num) * Number(item.price)).toFixed(0)
                }
            })
            this.form.contract_price = (count_price).toFixed(0)
            this.form.total_price = (count_price).toFixed(2)
        },
        // 获取分类
        async getCate() {
            var res = await this.$API.goods.goodsCate.all.get();
            this.cateList = res.data
        },
        // 获取单位
        async getUnit() {
            var res = await this.$API.goods.goodsUnit.all.get();
            this.unitList = res.data
        },
        // 获取销售人
        async getAdmin() {
            var res = await this.$API.system.admin.all.get();
            this.adminList = res.data;
        },
        async getClient() {
            var res = await this.$API.client.client.all.get();
            this.clientList = res.data;
        },
        async getColor(){
            var res = await this.$API.common.getDictData.get({ type: "color" });
            let array = []
            res.data.color.map(item=>{
                array.push({
                    id:Number(item.value),
                    name:item.name
                })
            })
            this.colorList = array;
        },
        async getDirection(){
            var res = await this.$API.common.getDictData.get({ type: "direction" });
            let array = []
            res.data.direction.map(item=>{
                array.push({
                    id:Number(item.value),
                    name:item.name
                })
            })
            this.directionList = array;
        },
        async goodsChange(row) {
            console.log('row :>> ', row);
            row.goods_model = row.goods_obj.goods_model
            row.goods_model_name = row.goods_obj.goods_model
            row.speed_ratio_name = row.goods_obj.speed_ratio_name
            row.flange_name = row.goods_obj.flange_name
            row.color_name = row.goods_obj.color_name
            row.hole = row.goods_obj.hole
            row.speed_ratio_id = row.goods_obj.speed_ratio_id
            row.flange_id = row.goods_obj.flange_id
            row.color_id = row.goods_obj.color_id
            row.price = row.goods_obj.sell_price
            row.total_price = row.goods_obj.sell_price
            row.ware_num = row.goods_obj.ware_num
            row.color_type = row.goods_obj.color_type
            row.direction_type = row.goods_obj.direction_type
            this.totalCompute()
        },
        clientChange(row){
            console.log('row :>> ', row);
            row.customer_id = row.customer_id.id
        },
        remarkInput(row) {
            if (row.remark1 != '') {
                row.price = ''
                row.total_price = ''
            }
        },
        // 账户
        async getAccount() {
            var res = await this.$API.finance.account.all.get();
            this.accountList = res.data;
        },
    }
}
</script>

<style lang="scss">
.formtable {
	.el-input__wrapper {
		padding: 0 5px !important;
	}

	// .el-table__body td.el-table__cell{
	//     padding: 0 !important;
	// }
	.el-table .cell {
		padding: 2px !important;
	}

	.el-table__row td {
		padding: 2px !important;
	}
}
</style>